//
//  QBGuidePageViewController.swift
//  QBLaunchAnimationAndVideo
//
//  Created by 乐启榜 on 16/7/22.
//  Copyright © 2016年 乐启榜. All rights reserved.
//

import UIKit
import AVFoundation


class QBGuidePageViewController: UIViewController {

    @IBOutlet weak var backgroundImageView: UIImageView!
    @IBOutlet weak var backView: UIView!
    
    
    let durationTime: NSTimeInterval = 5
    var player: AVPlayer!
    var playerItem: AVPlayerItem!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        initAvPlayer()
        doAnimation()
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    
    }
    
    func doAnimation() {
        
        var imageName: String?
        var image: UIImage?
        var images: [UIImage] = []
    
        // 将图片保存到数组
        var index = 0
        while index < 68 {
            imageName = "logo-" + String(format: "%03d", index)
            image = UIImage(named: imageName!)
            images.append(image!)
            index += 1
        }
        // 设置播放图片动画时间
        backgroundImageView.animationImages = images
        backgroundImageView.animationDuration = durationTime
        backgroundImageView.animationRepeatCount = 1
        backgroundImageView.startAnimating()
        
        UIView.animateWithDuration(0.7,delay: durationTime,options: .CurveEaseOut,animations: {
            self.backView.alpha = 1.0
            self.player.play()
        },completion: {
            finished in
            print("Animation end")
        })
    }
    
    func initAvPlayer() {
        // 添加路劲
        let path = NSBundle.mainBundle().pathForResource("welcome_video", ofType: "mp4")
        let url = NSURL(fileURLWithPath: path!)
        
        playerItem = AVPlayerItem(URL: url)
        player = AVPlayer(playerItem: playerItem)
        
        let playerLayer = AVPlayerLayer(player: player)
        playerLayer.frame = backView.frame
        playerLayer.videoGravity = AVLayerVideoGravityResizeAspect
        
        backView.layer.insertSublayer(playerLayer, atIndex: 0)
        backView.alpha = 0.0
        
        // 添加通知是为了循环播放视频
        NSNotificationCenter.defaultCenter().addObserver(self,
                                    selector: #selector(didFinishVideo(_: )),
                                    name: AVPlayerItemDidPlayToEndTimeNotification,
                                    object: playerItem)
    }
    
    func didFinishVideo(sender: NSNotification) {
        
        let item = sender.object as! AVPlayerItem
        
        item.seekToTime(kCMTimeZero)
        
        self.player.play()
        
    }



}
